package com.medicalproject.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.medical.pojo.User;
import com.medicalproject.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

import java.net.URLEncoder;
import java.util.List;

@RestController
public class LoginController {
    @Autowired
    UserService userService;

    public static com.aliyun.dingtalkoauth2_1_0.Client authClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    /**
     * 获取用户token
     * @param authCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public RedirectView getAccessToken(@RequestParam(value = "authCode") String authCode, HttpServletResponse response) throws Exception {
        com.aliyun.dingtalkoauth2_1_0.Client client = authClient();
        GetUserTokenRequest getUserTokenRequest = new GetUserTokenRequest()
                .setClientId("dingfjzkmnv6dffwboij")
                .setClientSecret("1Ya2R0Kv6Nh34tbeAZWnrwPRsD2mhzoHK8rUnhLGxqCHA76BImUgogdm3ej5-2gz")
                .setCode(authCode)
                .setGrantType("authorization_code");

        GetUserTokenResponse getUserTokenResponse = client.getUserToken(getUserTokenRequest);
        String accessToken = getUserTokenResponse.getBody().getAccessToken();

        // 获取用户信息并重定向到首页
        String userInfo = getUserinfo(accessToken);
        String phone = JSON.parseObject(userInfo).getString("mobile");
        String username=JSON.parseObject(userInfo).getString("nick");
        System.out.println("用户名："+username);
        System.out.println("手机号："+phone);
        User user = new User();
        user.setUsername(username);
        user.setPhone(phone);
        user.setPassword("123456");
        user.setPid(3);
        List<User> list=userService.findAll();
        String encodedParam = URLEncoder.encode(username, "UTF-8");
        for (User user1 : list) {
            if (user1.getUsername().equals(username)||user1.getPhone().equals(phone)) {
                System.out.println("登陆过");
                RedirectView redirectView = new RedirectView();
                redirectView.setUrl("http://localhost:8081/#/medical?username="+encodedParam+"&phone="+phone+"&pid="+ user.getPid());
                return redirectView;
            }
        }
        System.out.println("添加成功");
        userService.add(user);
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://localhost:8081/#/medical?username="+encodedParam+"&phone="+phone+"&pid="+ user.getPid());
        return redirectView;


        // 这里可以根据需要处理用户信息


//        response.setCharacterEncoding("UTF-8");
        // 设置内容类型，这里是HTML
        // 重定向到首页


    }

    public static com.aliyun.dingtalkcontact_1_0.Client contactClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkcontact_1_0.Client(config);
    }

    /**
     * 获取用户个人信息
     * @param accessToken
     * @return
     * @throws Exception
     */
    public String getUserinfo(String accessToken) throws Exception {
        com.aliyun.dingtalkcontact_1_0.Client client = contactClient();
        GetUserHeaders getUserHeaders = new GetUserHeaders();
        getUserHeaders.xAcsDingtalkAccessToken = accessToken;
        String me = JSON.toJSONString(client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody());
        System.out.println(me);
        return me;
    }
}